const app = getApp()

Page({
  data: {
    tab: 0, /* 当前选中Tab项*/
    item: 0, /* 当前选中的swiper-item-id */
    playlist: [{
      id: 1, title: '赤伶', singer: "赤伶", src: 'http://localhost:3000/赤伶.mp3',
      coverImgUrl: '/images/cover.jpg'
    },
    {
      id: 1, title: '晴朗', singer: "晴朗", src: 'http://localhost:3000/晴朗.mp3',
      coverImgUrl: '/images/cover.jpg'
    }],
    state: 'paused',
    playIndex: 0,
    play: {
      currentTime: '00:00',
      duration: '00:00',
      percent: 19,
      title: '你好',
      singer: 'hello',
      coverImgUrl: '/images/cover.jpg'
    }
  },
  /**
   * 切换 swiper -item
   * @param {*} e 
   */
  changeItem(e) {
    this.setData({
      item: e.target.dataset.item
    })
  },
  /**
   * 切换 swiper -item
   * @param {*} e 
   */
  changeTab(e) {
    this.setData({
      tab: e.detail.current // 当前项
    })
  },
  onLoad() {

  },
  play() {
    this.audioCtx.play()
    this.setData({ state: 'running' })
  },

  pause() {
    this.audioCtx.pause()
    this.setData({ state: 'paused' })
  },
  next() {
    var index = this.data.playIndex >= this.data.playlist.length - 1 ? 0 : this.data.playIndex + 1;
    this.setMusic(index)
    if (this.data.state === 'running') {
      this.play()
    }
  },
  audioCtx: null,
  onReady() {
    this.audioCtx = wx.createInnerAudioContext()
    this.setMusic(0)
    this.audioCtx.onError((error) => {
      console.log(error)
    })
    this.audioCtx.onEnded((res) => {
      this.next()
    })
    this.audioCtx.onPlay(() => { })
    this.audioCtx.onTimeUpdate(() => {
      this.setData({
        'play.currentTime': FormatTime(this.audioCtx.duration),
        'play.duration': FormatTime(this.audioCtx.currentTime),
        'play.percent': this.audioCtx.currentTime / this.audioCtx.duration * 100,
      })
    })
    function FormatTime(time) {
      var munite = Math.floor((time / 60) % 60);
      var second = Math.floor(time) % 60;
      return ((munite >= 10 ? '' + munite : '0' + munite) + ':' + (second >= 10 ? '' + second : '0' + second))
    }
  },

  setMusic: function (index) {
    console.log(this.data.playlist);
    var music = this.data.playlist[index]
    this.audioCtx.src = music.src
    this.setData({
       playIndex: index,
      'play.title': music.title,
      'play:coverImgUrl': music.singer,
      'play.currentTime': '00:00',
      'play.duration': '00:00',
      'play.percent': 0,
      'play.singer': music.singer
    })

  },
  sliderChange(e){
    var second = e.detail.value * this.audioCtx.duration /100
    this.audioCtx.seek(second)
  },
  change(e){
    this.setMusic(e.currentTarget.dataset.index)
    this.play()
  }
})
